<template>
  <div>
    <div class="card_header">
      <span style="font-size: 22px">Nation: </span
      ><span style="font-size: 22px; font-weight: bold; color: brown">{{
        nation["indicator"]
      }}</span>
    </div>
    <div v-loading="loading">
      <template v-for="(v, i) in columnNames">
          <el-row :gutter="10" :key="i" type="flex" align="middle">
            <el-col :span="8" >
              <span style="font-size: 18px;" :key="i">{{ v }}: </span>
            </el-col>
            <el-col :span="6">
              <div
                style="padding: 5px"
                :class="{ active: isActive[i] }"
              >
                <el-input v-model="columnData[v]"></el-input>
              </div>
            </el-col>
            <el-col :span="8">
              <el-button
                type="primary"
                size="small"
                class="item"
                @click="fit(v, i)"
              >
                修改
              </el-button>
            </el-col>
          </el-row>
      </template>
    </div>
  </div>
</template>

<script>
import colorSet from '../assets/js/color'

import d3 from 'd3'
export default {
  name: 'App',
  props: ['nation', 'layout'],
  components: {
  },
  updated () {
    // console.log(this.nation)
  },
  data () {
    return {
      isActive: [],
      loading: false,
      locations: [],
      interValues: [],
      interName: "",
      columnData: {}, // 与columnNames 对应的数据
      columnNames: ['population', 'surface area (Km2)', 'GINI index', 'happy planet index',
        'human development index', 'world happiness report score', 'sustainable economic development assessment (SEDA)',
        'GDP (billions PPP)', 'GDP per capita (PPP)', 'GDP growth(annual %)', 'health expenditure % of GDP',
        'health expenditure per person', 'education expenditure% of GDP', 'education expenditure per person',
        'school life expectancy (YEARS)', 'unemployment (%)', 'government spending score',
        'government expenditure (% of GDP)', 'political rights score', 'civil liberties score',
        'political stability & absence of violence', 'government effectiveness', 'regulatory quality',
        'rule of law', 'control of corruption', 'judicial effectiveness score', 'government integrity score',
        'property rights score', 'tax burden score', 'overall economic freedom score', 'financial freedom score', 'women MPs (% of all MPs)']

    }
  },
  mounted () {
    // console.log("nation", this.props.nation)
    this.columnData = JSON.parse(JSON.stringify(this.nation))
    for (let i = 0; i < this.columnNames.length; i++) {
      this.isActive.push(false)
    }
    // console.log('layout', this.layout)
  },
  watch: {
    nation: function (newVal) {
      this.columnData = JSON.parse(JSON.stringify(newVal))

      // console.log("columnData", this.columnData)
    },
  },
  methods: {
    fit (cName, index) {
      for (let i = 0; i < this.columnNames.length; i++) {
        this.isActive[i] = false
      }
      this.isActive[index] = true
      this.interName = cName
      this.loading = true
      this.$axios.post('/fit', {
        nation: this.columnData['indicator'],
        columnName: cName,
        newValue: parseFloat(this.columnData[cName])
      }).then(res => {
        console.log(res)
        this.locations = res.data.locations
        this.interValues = res.data.values
        console.log("locations", this.locations)
        console.log("interValues", this.interValues)
        this.draw()

        this.loading = false
      }).catch(err => {
        console.log(err)
        this.loading = false
      })
      this.columnData = JSON.parse(JSON.stringify(this.nation))
    },
    draw () {
      d3.select('#motionpath').remove()
      d3.select('#move_circle').remove()
      d3.selectAll('.newDot').remove()
      let width = this.layout.width - this.layout.margin.right - this.layout.margin.left
      let height = this.layout.height - this.layout.margin.top - this.layout.margin.bottom
      let xMin = this.layout.xMin
      let yMin = this.layout.yMin
      let xRate = width / (this.layout.xMax - xMin)
      let yRate = height / (this.layout.yMax - yMin)
      let data = []
      for (let i = 0; i < this.locations.length; i++) {
        data.push({ 'location': this.locations[i], 'value': this.interValues[i] })
      }

      let line_generator = d3.svg.line()//d3中绘制曲线的函数
        .x(function (d) { return calcX(d[0]) })//曲线中x的值
        .y(function (d) { return calcY(d[1]) })//曲线中y的值
        .interpolate("cardinal")//把曲线设置光滑
      let newLocations = this.locations
      newLocations.unshift([this.nation.x, this.nation.y])
      d3.select('#svg')
        .append('path')
        .attr('id', 'motionpath')
        .attr('d', line_generator(newLocations))
      d3.select('#svg')
        .append('circle')
        .attr('id', 'move_circle')
        .attr('r', 5)
        .attr('fill', colorSet.newCircleColor)
        .append('animateMotion')
        .attr("id", "animimg")
        .attr("repeatCount", "indefinite")
      d3.select('#svg').selectAll('.newDot').data(data)
        .enter()
        .append('circle')
        .attr('class', 'newDot')
        .attr('cx', d => calcX(d.location[0]))
        .attr('cy', d => calcY(d.location[1]))
        .attr('r', 5)
        .attr('fill', colorSet.newCircleColor)
        .on('mouseout', this.leave(this.nation[this.interName]))
        .on('mouseover', d => this.updateInterpolation(d.value))
      let dPath = d3.select('#motionpath').attr('d')
      console.log(dPath)
      d3.select('#animimg')
        .attr('dur', '10s')
        .attr('path', dPath)
      function calcX (x) {
        return (x - xMin) * xRate
      }
      function calcY (y) {
        return (y - yMin) * yRate
      }
    },
    updateInterpolation (value) {
      console.log("updateInterpolation", value)
      this.columnData[this.interName] = value
    },
    leave (value) {
      console.log("leave", value)
      this.columnData[this.interName] = value
    }
  }
}
</script>
<style>
.card_header {
  position: -webkit-sticky;
  position: sticky;
  top: 0;
  background: white;
  z-index: 5;
}
.row_container {
  display: flex;
  flex-direction: row;
  align-content: center;
}
.column_input {
  margin: 5px;
  flex-basis: 1;
  max-width: 50%;
}
.item {
  margin: 5px;
  height: auto;
}
.active {
  background-color: cornflowerblue;
}
path {
  fill: none;
  stroke: cornflowerblue;
  stroke-width: 2px;
}
</style>
